package game.module.sss.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.HallServer;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.CheatManager;
import game.module.offline.bean.PlayerOfflineCache;
import game.module.offline.logic.PlayerOfflineManager;
import game.module.sss.bean.SssRoom;
import game.module.sss.logic.SssDataManager;
import game.module.sss.logic.SssLogic;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageSss.C2SSSSJoinRoom;
import lua.LuaMessageSss.PushSSSPlayerJoin;
import lua.LuaMessageSss.S2CSSSJoinRoom;
import lua.LuaMessageSss.SSSMemberInfo;

@MsgCodeAnn(msgcode = C2SSSSJoinRoom.id, accessLimit = 500)
public class SssJoinRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(SssJoinRoomProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		C2SSSSJoinRoom reqMsg = C2SSSSJoinRoom.parse(request);
		String room_id = reqMsg.room_id;
		int playerId = hero.getId();
		logger.info("sss join room,playeyId={},room_id={}", playerId, room_id);
		// 是否在房间中
		boolean isInRoom = SssDataManager.getInstance().isPlayerInRoom(playerId);
		if (isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(102);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is fang not exist
		if (!SssDataManager.getInstance().checkRoomExist(room_id)) {
			S2ErrorCode respMsg = new S2ErrorCode(104);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		final SssRoom ddzRoom = SssDataManager.getInstance().getSssRoom(room_id);

		int fangka = hero.getPlayerBean().getFang_ka();
		int fangka_cost = ddzRoom.getRoomFee();
		if (ddzRoom.getRoomFeeType() == 2 && fangka < fangka_cost)// 赢家收费
		{
			S2ErrorCode respMsg = new S2ErrorCode(103);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (ddzRoom.getRoomFeeType() == 1 && fangka < fangka_cost / 2) {// AA
			S2ErrorCode respMsg = new S2ErrorCode(103);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// 人数已满
		if (ddzRoom.getPlayerList().size() >= ddzRoom.getPlayer_count()) {
			S2ErrorCode respMsg = new S2ErrorCode(105);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (ddzRoom.getIs_jindou() == 1 && hero.getPlayerBean().getJin_dou() < ddzRoom.getJindou() * ddzRoom.getRoundCount() * 5) {// 金豆房间
			S2ErrorCode respMsg = new S2ErrorCode(133);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (CheatManager.getInstance().checkCheatAndJoin(ddzRoom.getPrevent_cheat(), ddzRoom.getIps(), hero)) {
			return;
		}

		SssLogic.getInstance().addRoomPlayer(playerId, room_id);
		// ret
		S2CSSSJoinRoom respMsg = new S2CSSSJoinRoom();
		respMsg.room_id = room_id;
		respMsg.round_count = ddzRoom.getRoundCount();
		respMsg.anti_cheet = ddzRoom.getPrevent_cheat();
		respMsg.mapai = ddzRoom.getMapai();
		respMsg.daqiang = ddzRoom.getDaqiang();
		respMsg.sunzi_a = ddzRoom.getSunzi_a();
		respMsg.baodao = ddzRoom.getBaodao();
		respMsg.is_jindou = ddzRoom.getIs_jindou();
		respMsg.jindouNum = ddzRoom.getJindou();
		respMsg.player_count = ddzRoom.getPlayer_count();
		respMsg.add_color = ddzRoom.getAdd_color();
		respMsg.roomFeeType = ddzRoom.getRoomFeeType();
		// respMsg.jindou_type = ddzRoom.getJindou_type();
		respMsg.members = new SSSMemberInfo[ddzRoom.getPlayerList().size()];
		List<Integer> playerIdList = ddzRoom.getPlayerList();
		int i = 0;
		for (Integer aPlayerId : playerIdList) {
			PlayerOfflineCache poc = PlayerOfflineManager.getInstance().getPlayerOfflineCache(aPlayerId);
			long jindou = poc.getJindou();
			respMsg.members[i++] = new SSSMemberInfo(aPlayerId, poc.getHeadimg(), poc.getLevel(), poc.getSex().shortValue(), (int) jindou, poc.getName());
		}
		// data
		SssDataManager.getInstance().addPlayer(playerId, room_id);
		hero.writeAndFlush(respMsg.build(hero.alloc()));
		// push
		PushSSSPlayerJoin pushPlayerJoin = new PushSSSPlayerJoin();
		pushPlayerJoin.seat_index = (short) (ddzRoom.getPlayerList().size() - 1);
		long jindou = hero.getPlayerBean().getJin_dou();
		pushPlayerJoin.member_info = new SSSMemberInfo(playerId, hero.getPlayerBean().getHeadimg(), hero.getPlayerBean().getLevel(), hero.getPlayerBean().getSex().shortValue(),
				(int) jindou, hero.getPlayerBean().getName());
		for (Integer aPlayerId : playerIdList) {
			if (aPlayerId == playerId) {
				continue;
			}
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushPlayerJoin.build(pr.alloc()));
			}
		}
		// delay 2 seconds to start
		// HallServer.executorService.schedule(new Runnable() {
		//
		// @Override
		// public void run() {
		// if (ddzRoom.getPlayerList().size() >= 3) {
		// sendRoomStart(ddzRoom);
		// }
		// }
		// }, 2, TimeUnit.SECONDS);
	}

	private void sendRoomStart(SssRoom ddzRoom) {
		logger.info("sss start battle!");
		String rsLanHost = HallServer.getInstance().getServerConfig().getRsLanHost();
		int rsLanPort = HallServer.getInstance().getServerConfig().getRsLanPort();
		boolean reconnectRet = HallServer.getInstance().getLanClientManager().connect(rsLanHost, rsLanPort);
		if (reconnectRet) {
			HallServer.getInstance().getLanClientManager().sendSssStart2Rs(rsLanHost, rsLanPort, ddzRoom);
		} else {
			logger.error("connect 2 roomServer error!rsLanHost={},rsLanPort={}", rsLanHost, rsLanPort);
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// null
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// null
	}

}
